/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useEffect, useCallback, useRef } from "react";
import { connect } from "dva";
import { Button, Row, Col, Spin, Icon, Modal, Radio, message } from "antd";
import { isLegalData } from "@/utils/utils";
import { isEmpty } from "lodash";
import styles from "../style.less";

const name = "公众号/小程序";
const QrCodeScanPage = ({
  dispatch,
  hasAuth,
  changeBindRelation = false,
  getting_bind,
  goBack = () => {},
  qrCodeInfo,
  children,
  qr_data,
}) => {
  const [maskQr, setMaskQr] = useState(false);
  const [visible, setVisible] = useState(false);
  const [related, setRelated] = useState(false);
  const [selectVla, setSelectVla] = useState({});
  const { weixin = [], weixin_mini = [] } = qrCodeInfo;
  const timer = useRef();

  // 开始循环检测
  const startLoop = useCallback(
    (qrData = {}) => {
      let limitTimer = 0;
      const maxTimer = 5 * 60; // 5分钟
      setMaskQr(false);
      stopLoop();
      timer.current = setInterval(() => {
        limitTimer++;
        if (limitTimer >= maxTimer) {
          stopLoop();
          // 遮罩二维码
          setMaskQr(true);
          return;
        }
        checkScanCodeStatus(qrData);
      }, 1000);
    },
    [timer, stopLoop, checkScanCodeStatus]
  );

  const stopLoop = useCallback(() => {
    if (timer.current) {
      clearInterval(timer.current);
      timer.current = null;
    }
  }, []);

  // 获取绑定二维码
  const getBindCode = useCallback(
    () => {
      // 获取二维码，先关闭轮询
      stopLoop();
      dispatch({
        type: "platform/getPlatformBindCode",
      }).then(({ data }) => {
        if (data && data.url) {
          startLoop(data);
        }
      });
    },
    [dispatch, startLoop, stopLoop]
  );

  // 获取二维码内容
  const getQrcodeInfo = useCallback(
    (qrData = {}) => {
      dispatch({
        type: "platform/getQrCodeInfo",
        payload: {
          sceneId: qrData && qrData.sceneId,
        },
      }).then(res => {
        const { code } = res;
        if (code == 0) {
          setVisible(true);
        }
      });
    },
    [dispatch]
  );

  // 检查用户是否扫了二维码
  const checkScanCodeStatus = useCallback(
    (qrData = {}) => {
      dispatch({
        type: "platform/checkScanCodeStatus",
        payload: {
          sceneId: qrData && qrData.sceneId,
        },
        then: ({ data, code }) => {
          if (code == 0 && data == 1) {
            stopLoop();
            getQrcodeInfo(qrData);
          } else if (code == 1) {
            // 二维码失效
            stopLoop();
            setMaskQr(false);
          }
        },
      });
    },
    [dispatch, getQrcodeInfo, stopLoop]
  );

  useEffect(
    () => {
      if (!hasAuth || changeBindRelation) {
        stopLoop();
        dispatch({
          type: "platform/getPlatformList", // 检查是否有已绑定的平台
        }).then(res_ => {
          const { data: list } = res_;
          const hasBind = isLegalData(list, []).length > 0;
          setRelated(hasBind);

          dispatch({
            type: "platform/getPlatformBindCode", // 获取二维码信息
          }).then(res => {
            const { data } = res;
            if (!hasBind) {
              // 当没有绑定的平台则开始轮询
              startLoop(data);
            } else if (changeBindRelation && hasBind) {
              // 新增绑定时开启轮询
              startLoop(data);
            }
          });
        });
      } else {
        setRelated(hasAuth);
      }
      return () => {
        stopLoop();
      };
    },
    [hasAuth, dispatch, startLoop, stopLoop, changeBindRelation]
  );

  const onOk = useCallback(
    () => {
      if (!isEmpty(selectVla)) {
        dispatch({
          type: "platform/authPlatform",
          payload: {
            platform: selectVla,
          },
        })
          .then(res => {
            const { code, data } = res;
            if (code == 0 && data) {
              dispatch({
                type: "platform/getPlatformList", // 获取已绑定平台
              }).then(val => {
                const hasBind = isLegalData(val.data, []).length > 0;
                if (!hasBind) {
                  message.error("绑定失败！");
                  getBindCode(); // 绑定失败重新轮询二维码
                }
                setRelated(hasBind);
                // 新增关联后返回
                changeBindRelation && goBack();
              });
              setVisible(false);
            }
          })
          .catch(() => {
            getBindCode();
            setVisible(false);
          });
      } else {
        message.error("请选择公众号或者小程序");
      }
      setSelectVla({});
    },
    [selectVla, dispatch, goBack, changeBindRelation, getBindCode]
  );

  const onCancel = useCallback(
    () => {
      getBindCode();
      setVisible(false);
      setSelectVla({});
    },
    [getBindCode]
  );

  const onChange = useCallback(e => {
    setSelectVla(prev => ({
      ...prev,
      [e.target.name]: e.target.value,
    }));
  }, []);

  return related && !changeBindRelation ? (
    children
  ) : (
    <div className={styles.main}>
      <div className={styles.content}>
        <div style={{ textAlign: "center" }}>
          <Spin spinning={getting_bind}>
            {qr_data && qr_data.url ? (
              <div className={styles.maskQr}>
                {maskQr && (
                  <div onClick={getBindCode}>
                    <Icon type="redo" />
                  </div>
                )}
                <img src={qr_data.url} alt="" />
              </div>
            ) : (
              <div style={{ height: 130 }}>
                <h3>
                  获取二维码失败，请
                  <a onClick={getBindCode}>点击</a>
                  重新获取
                </h3>
              </div>
            )}
          </Spin>
          <p>
            请使用定制
            {name}
            管理微信扫描上方二维码进行关联
          </p>
          <p>
            如需定制
            {name}
            ，高效积累私域流量，
            <a
              href="https://m.kuaidihelp.com/Home/index?platform=wkd_mini-2#/customer"
              target="_blank"
              rel="noreferrer"
            >
              请点击此处联系客服定制
            </a>
          </p>
          {goBack &&
            hasAuth && (
              <Row gutter={[0, 20]}>
                <Col>注：已关联公众号状态下，使用新定制公众号的管理员微信扫码会切换关联对象</Col>
                <Col>
                  <Button type="primary" onClick={goBack}>
                    返回
                  </Button>
                </Col>
              </Row>
            )}
        </div>
      </div>
      <Modal
        title="请选择需要绑定的公众号/小程序"
        destroyOnClose
        onOk={onOk}
        onCancel={onCancel}
        visible={visible}
      >
        <Row>
          <Col span={24}>
            公众号：
            {weixin.length > 0 ? (
              <Radio.Group
                name="weixin"
                onChange={onChange}
                options={weixin.map(val => ({
                  label: val.platformName,
                  value: val.platform,
                }))}
              />
            ) : (
              "暂无公众号"
            )}
          </Col>
          <Col span={24}>
            小程序：
            {weixin_mini.length > 0 ? (
              <Radio.Group
                name="weixin_mini"
                onChange={onChange}
                options={weixin_mini.map(val => ({
                  label: val.platformName,
                  value: val.platform,
                }))}
              />
            ) : (
              "暂无小程序"
            )}
          </Col>
        </Row>
      </Modal>
    </div>
  );
};

export default connect(({ loading, platform }) => ({
  platform,
  qr_data: platform.qrData,
  hasAuth: platform.hasBind,
  qrCodeInfo: platform.qrCodeInfo,
  getting_list: loading.effects["platform/getPlatformList"],
  getting_bind: loading.effects["platform/getPlatformBindCode"],
}))(React.memo(QrCodeScanPage));
